#include <nds.h>
#include <dswifi7.h>

#include "command7.h"

// -----------------------------------
void fifoMyDataHandler(int num_bytes, void * userdata)
// -----------------------------------
{
	Command command;
	int read = fifoGetDatamsg(FIFO_USER_01, sizeof(Command), (u8*)(&command));

	if (read == sizeof(Command))
	{
		switch (command.commandType)
		{
			case ARM7_SET_CHANNEL:
				DoARM7_SetChannel(&command.setChannel);
				break;
			case ARM7_UPDATE_CHANNEL:
				DoARM7_UpdateChannel(&command.updateChannel);
				break;
			case ARM7_STOP_CHANNEL:
				DoARM7_StopChannel(command.stopChannel);
				break;
		}
	}
}

#undef SOUND_FREQ
#define SOUND_FREQ(n)		(0x10000 - (16777216 / (n)))

// -----------------------------------
void DoARM7_SetChannel(SetChannelCommand* ps)
// -----------------------------------
{
  int channel = ps->channel;

  SCHANNEL_TIMER(channel) = SOUND_FREQ(ps->frequency);
  SCHANNEL_LENGTH(channel) = ps->length >> 2;
  SCHANNEL_CR(channel) = SCHANNEL_ENABLE | SOUND_REPEAT | SOUND_FORMAT_16BIT | SOUND_PAN(ps->pan);
}

// -----------------------------------
void DoARM7_UpdateChannel(UpdateChannelCommand* ps)
// -----------------------------------
{
	int channel = ps->channel;
	SCHANNEL_SOURCE(channel) = (u32)ps->data;
	SCHANNEL_CR(channel) |= SOUND_VOL(ps->volume);
}

// -----------------------------------
void DoARM7_StopChannel(int channel)
// -----------------------------------
{
	SCHANNEL_CR(channel) = 0;
}
